package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrdersPageQueryVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;


    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //查询地址是否为空
        Long userId = BaseContext.getCurrentId();
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.findByIdAndUserId(addressBookId, userId);
        if (addressBook==null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询购物车是否为空
        List<ShoppingCart> shoppingCart = shoppingCartMapper.findShoppingCartUserById(userId);
        if (shoppingCart==null || shoppingCart.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //封装订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.REFUND);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
            //查询用户数据并封装
        User user = userMapper.findUserByUserId(userId);
        orders.setUserName(user.getName());
            //从地址簿获取地址
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());
        //添加订单
        orderMapper.save(orders);
        //封装订单详情
        List<OrderDetail> list = shoppingCart.stream().map(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailMapper.saveDetailList(list);
        //删除购物车
        shoppingCartMapper.deleteCart(userId);
        //封装要返回的订单信息
        return  OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 提交订单
     * @param
     * @return
     */
    /*@Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //1.查询地址信息
        AddressBook addressBook = addressBookMapper.findByIdAndUserId(ordersSubmitDTO.getAddressBookId(), userId);
        //2.判断用户有没有填写地址
        if (addressBook == null) {
            //出错
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //2.查询当前用户有没有在购物车加入数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findShoppingCartUserById(userId);
        //没数据
        if (shoppingCarts == null||shoppingCarts.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //3.存订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //绑定数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);


        //查询user表 获取微信用户名
        User userByOpenid = userMapper.findUserByUserId(userId);
        orders.setUserName(userByOpenid.getName());
        //查询地址簿,获取信息
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());

        //添加订单
        orderMapper.save(orders);

        //4.存订单详情
        //注意事项 => 订单详情的数据来自于购物车数据
        List<OrderDetail> orderDetailList = shoppingCarts.stream()
                .map(shoppingCart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(shoppingCart,orderDetail);
                    orderDetail.setId(null); //这里一定要注意id的问题!!!
                    //设置订单id
                    orderDetail.setOrderId(orders.getId());
                    return orderDetail;
                })
                .collect(Collectors.toList());
        orderDetailMapper.saveDetailList(orderDetailList);

        //5.删除购物车
        shoppingCartMapper.deleteCart(userId);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCartMapper.delShoppingCart(shoppingCart);

        //6.组装数据返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

    }*/






    //订单结账,修改订单
    @Override
    public void update(String orderNum) {
        //1.根据订单号查询订单
        Orders orders = orderMapper.findOrderByOrderNum(orderNum);
        if(orders == null){
            //抛出异常 订单出问题
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.修改状态
        orders.setStatus(Orders.TO_BE_CONFIRMED); //待接单
        orders.setCheckoutTime(LocalDateTime.now()); //结账时间
        orders.setPayStatus(Orders.PAID);
        orderMapper.update(orders);

        //3.发送给前端(商家管理端 => 提示 有人下单并且支付了,需要商家接单)
        //type
        //orderId
        //content
        HashMap<String,Object> param = new HashMap<>();
        param.put("type",1);
        param.put("orderId",String.valueOf(orders.getId()));
        param.put("content",orders.getNumber());
        try {
            webSocketServer.sendToAllClient(new ObjectMapper().writeValueAsString(param));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    /**再来一单
     *
     * @param id
     */
    @Override
    public void moreOrder(Long id) {
        Orders orders = orderMapper.orderById(id);
       /* orders.setId(null);
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.save(orders);*/
        List<OrderDetail> dishs = orderDetailMapper.findDishs(orders.getId());
        Long userId = BaseContext.getCurrentId();

        dishs.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCartMapper.add(shoppingCart);
        });

    }

    /**
     * 用户端取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) throws Exception {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);
        // 判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() == 1 || orders.getStatus() == 6 ) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = new Orders();
        orders.setId(orders.getId());
        /*// 退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            weChatPayUtil.refund(
                    orders1.getNumber(),
                    orders1.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            //支付状态修改
            orders.setPayStatus(Orders.REFUND);
        }*/
        //支付状态修改
        orders.setPayStatus(Orders.REFUND);
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //根据状态查询订单
        Page<Orders> byStatus = orderMapper.findByStatus(ordersPageQueryDTO.getStatus());
        List<Orders> ordersList = byStatus.getResult();
        //判断是否为空
        if (ordersList != null && ordersList.size() > 0) {
            List<OrdersPageQueryVO> collect = ordersList.stream().map(orders -> {
                //创建一个返回对象
                OrdersPageQueryVO ordersPageQueryVO = new OrdersPageQueryVO();
                //将查询的信息复制到ordersPageQueryVO中
                BeanUtils.copyProperties(orders, ordersPageQueryVO);
                //查询订单明细表
                List<OrderDetail> orderDetailList = orderDetailMapper.findDishs(orders.getId());
                //将订单明细存入返回对象
                ordersPageQueryVO.setOrderDetailList(orderDetailList);
                return ordersPageQueryVO;
            }).collect(Collectors.toList());

            PageResult pageResult = new PageResult(byStatus.getTotal(), collect);
            return pageResult;
        }

        ArrayList<OrdersPageQueryVO> ordersPageQueryVOS = new ArrayList<>();
        return new PageResult(byStatus.getTotal(), ordersPageQueryVOS);
    }

    @Override
    public OrdersPageQueryVO findOrderDetail(Long id) {
        OrdersPageQueryVO orderPageQueryVO = new OrdersPageQueryVO();
        //查询订单
        Orders order = orderMapper.findOrderById(id);
        BeanUtils.copyProperties(order,orderPageQueryVO);
        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findDishs(id);
        orderPageQueryVO.setOrderDetailList(orderDetailList);
        return orderPageQueryVO;
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.orderById(id);
        HashMap<String,Object> param = new HashMap<>();
        param.put("type",2);
        param.put("orderId",String.valueOf(orders.getId()));
        param.put("content",orders.getNumber());
        try {
            webSocketServer.sendToAllClient(new ObjectMapper().writeValueAsString(param));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
